package logic

import (
	"context"
	"errors"
	"good/models/mysql"
	"good/pkg"

	"good/goodrpc/goodrpc"
	"good/goodrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUploadPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadPasswordLogic {
	return &UploadPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UploadPasswordLogic) UploadPassword(in *goodrpc.UploadPasswordRequest) (*goodrpc.UploadPasswordResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("account=?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("用户不存在")
	}

	if in.Password == pkg.Md5str(user.Password) {
		return nil, errors.New("新密码不能与旧密码一致")
	}
	mysql.DB.Debug().Updates(&user)

	return &goodrpc.UploadPasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
